<?php

namespace Lib\Core;

class Server extends \Home {

    public $app;

    public $module;

    public $func;

    public $token;

    public $params;

    public function start() {
        try {
            $this->app = $_POST['app'];
            \Main::$appNamespace = '\\' . $this->app . '\\';
            $this->module = $_POST['module'];
            $this->func = $_POST['func'];
            $this->params = json_decode($_POST['params'], true);
            $this->token = $_POST['token'];
            $configClass = \Main::$appNamespace . 'Config\Server';
            $secret = $configClass::SECRET;
            $this->verification($_POST['token'], $_POST['params'], $secret);
            $this->run();
        } catch (\Lib\Exception\SysExit $e) {
        } catch (\Exception $e) {
            $className = get_class($e);
            $this->responseSerialize(new $className($e->getMessage(), $e->getCode()));
        }
    }

    private function run() {
        $moduleClass = '\\' . $this->app . '\Module\\' . $this->module;
        $module = $moduleClass::instance();
        $result = call_user_func_array(array($module, $this->func), $this->params);
        if (is_object($result)) {
            $this->responseSerialize($result);
        } else {
            $this->response($result);
        }
    }

    private function verification($token, $params, $secret) {
        if ($token != md5(md5($secret) . $params)) {
            throw new \Exception('验证失败');
        }
    }

    private function response($result) {
        $this->setResponseType('MESSAGEPACK');

        echo msgpack_pack($result);
    }

    private function responseSerialize($e) {
        $this->setResponseType('SERIALIZE');
        $v = serialize($e);
        echo $v;
    }

    private function setResponseType($type) {
        echo $type;
        echo md5($this->token);
    }
}

spl_autoload_register(function($className) {
    $file = APP_DIR . '/Apps/' . $className . '.php';
    $file = str_replace('\\', '/', $file);
    if (is_readable($file)) {
        include_once $file;
    }
}, true, true);